const router = require('koa-router')()
const  User = require('../models/userSchema')
const util = require('../utils/util')
const utils = require('../utils/util')
const jwt = require('jsonwebtoken')
const Counter = require('../models/counterSchema')
const md5=require('md5')
router.prefix('/users')

router.post('/login',async(ctx)=>{
//返回指定字段 方法1：const res = await User.findOne({userName,password},'userId usrName')
// 方法2：const res = await User.findOne({userName,password},{userId:1,userName:0}) 1代表返回 0代表不返回
// 方法3：const res = await User.findOne({userName,password}。select('userId))
 try{
  // console.log(ctx.request.body)
  const { userName,password} = ctx.request.body
  const res = await User.findOne({
    userName,
    password
  })
  if(res){
    const data = res._doc
    const token = jwt.sign({
    data: data
  }, 'jason', { expiresIn: '1h'});
    data.token = token
    ctx.body= utils.success(data)
  }else{
    ctx.body= utils.fail('用户名或者密码不正确')
  }
}catch(error){
  ctx.body= utils.fail(error.msg)
}
})

router.get('/list', async(ctx)=>{
  const {userId,userName,state} = ctx.request.query
  const {page,skipIndex} = utils.pager(ctx.request.query)
  let params = {}
  if(userId) params.userId = userId
  if(userName) params.userName = userName
  if(state&&state!='0') params.state= state
  try{
    const query = User.find(params,{_id:0,password:0})
    const list = await query.skip(skipIndex).limit(page.pageSize)
    const total = await User.countDocuments(params)
    ctx.body = util.success({
      page:{
        ...page,
        total
      },
      list
    })
  }catch(error){
    ctx.body = util.fail(`查询异常${error.stack}`)
  }
})

router.post('/delete',async(ctx)=>{
  const {userIds} = ctx.request.body
  const res = await User.updateMany({userId:{$in:userIds}},{state:2})
  if(res.modifiedCount){
    ctx.body=util.success(res,`共删除成功${res.modifiedCount}条`)
    return
  }
  ctx.body=util.fail('删除失败')
})

router.post('/operate',async(ctx)=>{
  const {userId,userName,userEmail,mobile,job,state,roleList,deptId,action} = ctx.request.body
  if(action =='add'){
    if(!userName||!userEmail){
      ctx.body=util.fail('参数错误')
      return
    }else{
      
    }
    const res = await User.findOne({$or:[{userName},{userEmail}]},'_id userName userEmail')
      if(res) {
        ctx.body = util.fail(`检测到有重复的用户，信息如下${res.userName}-${res.userEmail}`)
      }else{
        try{
          const doc = await Counter.findOneAndUpdate({_id:'userId'},{$inc:{sequence_value:1}})
          const user = new User({
            userId: doc.sequence_value,
            userName,
            userPwd: md5('123456'),
            userEmail,
            role: 1,
            roleList,
            state,
            job,
            deptId,
            mobile
          })
          user.save()
          ctx.body=util.success({},'用户创建成功')
        }catch(error){
          ctx.body = util.fail(error.stack, '用户创建失败')
        }
      }
    
  }else{
    if(!deptId){
      ctx.body = util.fail('部门不能为空', util.CODE.PARAM_ERROR)
      return
    }
    try{
      const res = await User.findOneAndUpdate({userId},{ mobile, job, state, roleList, deptId })
      ctx.body = util.success(res,'更新成功')
      return  
    }catch(error){
      ctx.body= util.fail('更新失败')
    }
  }
})
module.exports = router
